#include <event2/listener.h>
#include <event2/bufferevent.h>
#include <event2/buffer.h>


#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>


#define LISTEN_BACKLOG 10
#define PORT 9999


static void accept_conn_cb(struct evconnlistener *listener, evutil_socket_t fd, struct sockaddr* addr, int len, void *ptr) {
	printf("aaaaaaaaaaaaaaaaaaa");
	printf("accept a link");
	/* get libevent event_base from listener */
	struct event_base* base = evconnlistener_get_base(listener);
	printf("accept a link");
}

static void acceptErr(struct evconnlistener *listener,void *arg) {
	//获取base
	struct event_base *base = evconnlistener_get_base(listener);
	//获取错误字符
	int err = EVUTIL_SOCKET_ERROR();

	fprintf(stderr,"Get Error %d (%s)\n",err,evutil_socket_error_to_string(err));

	event_base_loopexit(base,NULL);
	//如果有多个监听，只把这个监听端口shutdown
}



int main(int argc, char **argv) {
#ifdef WIN32
	WSADATA wsa_data;
	WSAStartup(0x0201, &wsa_data);
#endif

	//evthread_use_windows_threads();//enable threads

	struct event_base *base;
	struct evconnlistener *listener;
	struct sockaddr_in sin;

	base = event_base_new();
	if (!base) {
		puts("Couldn't open event base");
		return 1;
	}

	// init addr 初始化绑定地址和端口
	memset(&sin, 0, sizeof(sin));
	sin.sin_family = AF_INET;
	sin.sin_addr.s_addr = htonl(0);
	sin.sin_port = htons(PORT);

	listener = evconnlistener_new_bind(base, accept_conn_cb, (void *)base, LEV_OPT_CLOSE_ON_FREE | LEV_OPT_REUSEABLE, -1,(struct sockaddr*)&sin, sizeof(sin));
	// init a libevent listener 给event_base绑定地址和端口，设置监听属性，设置回调函数 （如果使用evconnlistenner_new函数的话需要自己来绑定端口和初始化socket，并把socket_fd传递给该函数）

	if (!listener) {
		fprintf(stderr, "Could not create a listener!\n");
		return 1;
	}

	evconnlistener_set_error_cb(listener,acceptErr);
	/* start loop for accept_conn_cb */

	event_base_dispatch(base);
	return 0;
}
